﻿using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using CoreEx.Common.Extensions;
using CoreEx.Database.Client;
using CoreEx.Database.Query;
using CoreEx.DynamicInvoker;
using LinFu.IoC;
using CoreEx.MicroMapper;

namespace CoreEx.Database.Linq.Implementation
{
    public class QueryProvider : QueryProviderBase
    {
        protected override object Execute(Expression expression)
        {
                        
            var translateresult = ExpressionTranslator.Translate(expression);

            ////Execute the translated query
            //Executor.Execute(translateresult);

            //Materialize the result into objects
            Materializer.Materilize(translateresult);


            //RelationMapper.MapRelations(translateresult);

            //var table =
            //    ServiceContainer.GetService<IDbCommand>(ConnectionName).ExecuteReader(
            //        (IQueryExpression) translateresult.DbExpression).ToTable();

            
            //var genericMapper = typeof (ITableMapper<>).MakeGenericType(translateresult.ProjectedType);


            //var mapper = ServiceContainer.GetService(genericMapper);
            
            //var applyMethod =
            //  mapper.GetType().GetMethods().Where(
            //      m => m.GetParameters().Any(p => typeof(IEnumerable).IsAssignableFrom(p.ParameterType))).FirstOrDefault();

            //var result = applyMethod.DynamicInvoke(mapper, new object[] { table });

            TranslateResult = translateresult;


            return translateresult.Result;
            
        }
    }
}
